<template>
  <el-date-picker :clearable="clearable" v-model="dateTime" class="sys-date-time-picker" type="datetime" value-format="timestamp" :format="format"
    :editable="false" :popper-class="popperClass" :picker-options="pickerOption" @change="timeChange">
  </el-date-picker>
</template>

<script>
  export default {
    props: {
      value: [Number, String],
      format: {
        type: String,
        default: 'yyyy-MM-dd HH:mm:ss'
      },
      type: {
        type: String,
        default: 'second'
      },
      clearable: {
        type: Boolean,
        default: false
      },
      disabledDate: Function
    },

    computed: {
      popperClass() {
        let type = this.type;
        return `sys-date-time-picker-popper date-time-picker-${this.type}-popper`
      }
    },

    watch: {
      value() {
        if (this.inputTime !== null) {
          this.inputTime = null;
          return;
        }
        this.dateTime = this.value;
      }
    },

    data() {
      let pickerOption = {};
      let disabledDate = this.disabledDate;
      if (disabledDate !== undefined) {
        pickerOption.disabledDate = disabledDate;
      }
      return {
        dateTime: this.value,
        inputTime: null,
        pickerOption
      };
    },

    methods: {
      timeChange() {
        let newValue = this.getTimeValue();
        let value = this.value;
        if (value === newValue) {
          return;
        }

        this.inputTime = newValue;
        this.$emit('input', newValue);
        this.$emit('change', newValue);
      },

      getTimeValue() {
        let dateTime = this.dateTime;
        if (dateTime === null) {
          return null;
        }
        let dateTimeMoment = this.$moment(dateTime);
        let newValue;
        let type = this.type;
        if (type === 'second') {
          newValue = dateTimeMoment.startOf('second').valueOf();
        } else if (type === 'minute') {
          newValue = dateTimeMoment.startOf('minute').valueOf();
        } else if (type === 'hour') {
          newValue = dateTimeMoment.startOf('hour').valueOf();
        }

        if (dateTime !== newValue) {
          this.dateTime = newValue;
        }
        return newValue;
      }
    }
  };

</script>

<style lang="scss">
  .sys-date-time-picker-popper {
    &.date-time-picker-minute-popper {
      .el-time-panel .el-time-spinner {
        >.el-time-spinner__wrapper {
          width: 50%;

          &:nth-child(3) {
            display: none;
          }
        }
      }
    }

    &.date-time-picker-hour-popper {
      .el-time-panel .el-time-spinner {
        >.el-time-spinner__wrapper {
          width: 100%;

          &:nth-child(2),
          &:nth-child(3) {
            display: none;
          }
        }
      }
    }
  }

</style>
